package com.homework.papertexting.controller;

import com.homework.papertexting.model.LoginResponse;
import com.homework.papertexting.model.User;
import com.homework.papertexting.model.RegisterRequest;
import com.homework.papertexting.model.LoginRequest;

import com.homework.papertexting.repository.UserRepository;
import com.homework.papertexting.util.JwtUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication; // 添加这一行
import org.springframework.security.core.context.SecurityContextHolder; // 添加这一行
import org.springframework.security.core.userdetails.UserDetails; // 添加这一行
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtUtil jwtUtil; // 注入 JwtUtil

    // 注册 (代码保持不变)
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody RegisterRequest registerRequest) {
        if (userRepository.existsByUsername(registerRequest.getUsername())) {
            return ResponseEntity
                    .status(HttpStatus.BAD_REQUEST)
                    .body(Map.of("message", "用户名已存在"));
        }

        if (userRepository.existsByEmail(registerRequest.getEmail())) {
            return ResponseEntity
                    .status(HttpStatus.BAD_REQUEST)
                    .body(Map.of("message", "电子邮箱已被注册"));
        }

        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setEmail(registerRequest.getEmail());
        user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));

        userRepository.save(user);

        return ResponseEntity.ok(Map.of("message", "注册成功"));
    }

    // 登录 (修改为生成并返回 JWT)
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        Optional<User> userOpt = userRepository.findByUsername(request.getUsername());

        if (userOpt.isEmpty() || !passwordEncoder.matches(request.getPassword(), userOpt.get().getPassword())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");
        }

        // 获取用户详情 (User 对象实现了 UserDetails 接口)
        User userDetails = userOpt.get();

        // 生成 JWT Token
        String jwtToken = jwtUtil.generateToken(userDetails);

        // 返回包含 Token 的响应对象
        return ResponseEntity.ok(new LoginResponse(jwtToken));
    }
    // ************ 添加这个新的需要认证的接口 ************
    @GetMapping("/me") // 使用 GET 请求，路径是 /api/auth/me (因为类上面的 @RequestMapping("/api/auth"))
    public ResponseEntity<?> getUserInfo() {
        // 从 Spring Security 的安全上下文中获取当前认证的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        // 检查 authentication 是否存在且已经过认证
        if (authentication != null && authentication.isAuthenticated()) {
            // getPrincipal() 方法通常返回 UserDetails 对象
            Object principal = authentication.getPrincipal();

            if (principal instanceof UserDetails) {
                // 从 UserDetails 对象中获取用户名
                String username = ((UserDetails) principal).getUsername();
                // 返回用户信息
                return ResponseEntity.ok("当前登录用户: " + username);
            } else {
                // 如果 principal 不是 UserDetails 类型，可能是匿名用户或其他情况
                // 但由于我们配置了 anyRequest().authenticated()，理论上到这里应该是认证过的 UserDetails
                return ResponseEntity.status(500).body("无法获取用户详情"); // 理论上不应该到这里
            }
        } else {
            // 如果 authentication 为 null 或未认证
            return ResponseEntity.status(401).body("用户未认证"); // 用户未提供有效 token 或认证失败
        }
    }

    @GetMapping("/health")
    public ResponseEntity<String> healthCheck() {
        return ResponseEntity.ok("Service is up and running");
    }

}